/**
 * Copyright (c) 2008, Julien PORTALIER
 * http://featherphp.googlecode.com/
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

/*if (!Textarea) { Textarea = {}; }*/
Textarea = {};

// autoresize of textarea elements
Textarea.AutoResize = new Class(
{
	initialize: function(textarea)
	{
		this.textarea = $(textarea);
		this.textarea.setStyle("overflow-y", "hidden");
		
		this.lastHeight     = 0;
		this.originalHeight = this.textarea.getSize().y;
		
		this.textarea.addEvent("keypress", this._autoResize.bind(this));
		this.textarea.addEvent("click",    this._autoResize.bind(this));
		
		this._setSize();
	},
	
	_autoResize: function()
	{
		$clear(this.timer);
		this.timer = this._setSize.delay(100, this);
	},
	
	_setSize: function()
	{
		if (!this.fake)
		{
			// we use a fake element to determine textarea"s height
			this.fake = new Element("textarea",{
				'class': 'fake',
				'styles': {
					"font-family": this.textarea.getStyle("font-family"),
					"font-weight": this.textarea.getStyle("font-weight"),
					"font-style":  this.textarea.getStyle("font-style"),
					"font-size":   this.textarea.getStyle("font-size"),
					"line-height": this.textarea.getStyle("line-height"),
					"width":       this.textarea.offsetWidth,
					"visibility":  "hidden",
					"height":   0,
					'margin':   0,
					'padding':  0,
					'position': 'absolute',
					'top':      this.textarea.offsetTop,
					'left':     this.textarea.offsetLeft,
					'z-index':  -1
				}
			}).injectAfter(this.textarea);
		}
		this.fake.value = this.textarea.value + "\n\n";
		
//		var maxHeight = window.getSize().y * 0.7;
		var height = this.fake.getScrollSize().y;
		if (height != this.lastHeight)
		{
//			if (height <= maxHeight)
//			{
//				this.textarea.setStyle("overflow-y", "hidden");
				this.textarea.setStyle("height", (height > this.originalHeight) ? height : this.originalHeight+ "px");
				this.lastHeight = height;
//			}
//			else if (maxHeight != this.lastHeight)
//			{
//				this.textarea.setStyle("height", maxHeight + "px");
//				this.textarea.setStyle("overflow-y", "");
//			}
		}
	}
});

// auto binds textareas
window.addEvent("domready", function()
{
	$$(".auto-resize textarea, textarea.auto-resize").each(function(textarea) {
		new Textarea.AutoResize(textarea);
	});
});
